import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import * as authActions from 'redux/modules/auth';

@connect(
  state => ({
    user: state.auth.user,
    working: state.auth.working,
    error: state.auth.error
  }),
  authActions)
export default class Login extends Component {
  static propTypes = {
    user: PropTypes.object,
    login: PropTypes.func,
    error: PropTypes.object,
    working: PropTypes.bool,
    logout: PropTypes.func,
    click: PropTypes.func,
    clearError: PropTypes.func
  }

  handleSubmit = (event) => {
    event.preventDefault();
    let username = this.refs.username.value;
    let password = this.refs.password.value;
    this.props.login({ username, password });
    username = '';
    password = '';
  }

  handleClearError = () => {
    if (this.props.error) {
      this.props.clearError();
    }
  }

  renderButton() {
    if (this.props.working) {
      return (
        <button className="btn btn-info" disabled="disabled" onClick={this.handleSubmit}>
          <i className="fa fa-spinner fa-pulse"></i> 登录中...
        </button>
      );
    }
    if (this.props.error && this.props.error.code === 101) {
      return (
        <button className="btn btn-danger" onClick={this.handleSubmit}>
          <i className="fa fa-exclamation-triangle"/> 用户名/密码错误
        </button>
      );
    }
    if (this.props.user) {
      return (
        <button className="btn btn-success" onClick={this.handleSubmit}>
          <i className="fa fa-check-square"/> 登录成功
        </button>
      );
    }
    return (
      <button className="btn btn-primary" onClick={this.handleSubmit}>
        <i className="fa fa-sign-in"/> 登录
      </button>
    );
  }
  render() {
    const { user, logout, click } = this.props;
    const styles = require('./Login.scss');
    return (
      <div className={styles.loginPage}>
        <Helmet title="Login"/>
        <h1 onClick={click}>Login</h1>
        {!user &&
        <div>
          <form className="login-form form-inline" onSubmit={this.handleSubmit}>
            <div className="form-group">
              <input type="text" ref="username" onChange={this.handleClearError} placeholder="用户名" className="form-control"/>
              <input type="password" ref="password" onChange={this.handleClearError} placeholder="密码" className="form-control"/>
            </div>
            {this.renderButton()}
          </form>
        </div>
        }
        {user &&
        <div>
          <p>You are currently logged in as {user.username}.</p>

          <div>
            <button className="btn btn-danger" onClick={logout}><i className="fa fa-sign-out"/>{' '}Log Out</button>
          </div>
        </div>
        }
      </div>
    );
  }
}
